package com.aloha.springframework.beans.factory.support;

import com.aloha.springframework.beans.BeansException;
import com.aloha.springframework.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * @author DaiZhiHeng
 * @description 使用CGLIB创建对象
 * @date 2023/7/4 8:46
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(String beanName, BeanDefinition beanDefinition, Constructor<?> constructor, Object[] args) throws BeansException {
        Enhancer enhancer = new Enhancer();
        // 设置父类
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        // NoOp：对于创建的对象的方法，什么也不做
        enhancer.setCallback(NoOp.INSTANCE);
        if (constructor == null) return enhancer.create();
        return enhancer.create(constructor.getParameterTypes(), args);
    }
}
